package project.dao.impl;

import project.bean.UserBean;
import project.dao.IUserDAO;

import java.sql.SQLException;

public class UserDAOImpl extends BaseDAO implements IUserDAO {
    /**
     * 通过结果集填充一个用户对象
     *
     * @return 用户实例
     * @throws SQLException
     */
    private UserBean getUser() throws SQLException {
        UserBean userBean = new UserBean();
        userBean.setId(rs.getString("pk_id"));
        userBean.setBalance(rs.getDouble("u_balance"));
        return userBean;
    }

    /**
     * 登陆
     *
     * @param id  账号
     * @param pwd 密码
     * @return 用户对象，如果登陆失败，返回 null
     */
    @Override
    public UserBean login(String id, String pwd) {
        this.setConnection();
        String sql = "select * from t_user where pk_id=? and u_password=?";
        UserBean userBean = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, id);
            ps.setObject(2, pwd);
            rs = ps.executeQuery();
            if (rs.next()) {
                userBean = getUser();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeConnection();
        }
        return userBean;
    }

    /**
     * 通过账号修改余额
     *
     * @param id
     * @param money
     */
    @Override
    public void update(String id, double money) {
        this.setConnection();
        String sql = "update t_user set u_balance=u_balance+? where pk_id=? ";
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, money);
            ps.setObject(2, id);
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeConnection();
        }
    }

    /**
     * 通过账号获取用户
     *
     * @param id 账号
     * @return
     */
    @Override
    public UserBean getUserById(String id) {
        this.setConnection();
        String sql = "select * from t_user where pk_id=? ";
        UserBean userBean = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, id);
            rs = ps.executeQuery();
            if (rs.next()) {
                userBean = getUser();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeConnection();
        }
        return userBean;
    }
}
